package com.woniuxy.yogaapp.handler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniuxy.yogaapp.pojo.Pocket;
import com.woniuxy.yogaapp.service.PocketService;
import com.woniuxy.yogaapp.util.AlipayConfig;
import com.woniuxy.yogaapp.util.ShiroSession;

@Controller
@RequestMapping("/pocket")
@Scope("prototype")
public class PocketHandler {
	@Resource
	private PocketService pocketService;
	private int uuid;
	private int mmoney;

	/**
	 * 查询该用户的钱包
	 */
	// @RequiresRoles(value={"admin"})
	@RequestMapping("/showPocket")
	@ResponseBody
	public Pocket showPocket() {
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		Pocket pocket = new Pocket();
		pocket.setPuid(uid);
		Pocket po = pocketService.findPocketByPuid(pocket);
		if (po == null) {
			po = new Pocket();
		}
		return po;

	}

	/**
	 * 用户点击钱包 判断该用户是否开通了钱包
	 */
	@RequestMapping("/pocket")
	@ResponseBody
	public String userPocket() {
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		Pocket pocket = new Pocket();
		pocket.setPuid(uid);
		Pocket po = pocketService.findPocketByPuid(pocket);
		if (po != null) {

			return "已开通钱包！";
		}
		return "未开通钱包！";
	}

	/**
	 * 开通钱包功能 需要前端传来支付密码
	 * 
	 */
	@RequestMapping("/openPocket")
	@ResponseBody
	public String openPocket(Pocket pocket) {
		String result = "开通失败！";
		if (pocket.getPass() == null || pocket.getPass().length() == 0) {
			return "支付密码不能为空！";
		}
		String result1 = userPocket();
		if (result1.contains("已开通")) {
			return "你已开通钱包，不能重复开通！";
		}
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		pocket.setPuid(uid);
		result = pocketService.addPocket(pocket);
		return result;

	}

	/**
	 * 绑定银行卡 银行卡号 支付密码
	 */
	@RequestMapping("/bindingBankCard")
	@ResponseBody
	public String bindingBankCard(Pocket pocket) {
		String result = "绑定失败！";
		// 验证银行卡号
		if (pocket.getBankcard() == null || pocket.getBankcard().length() == 0) {
			return "银行卡号不能为空！";
		}
		// 验证密码支付密码
		String pass = verifyPass(pocket);
		if (pass.contains("有误")) {
			return "支付密码有误！";
		} else if (pass.contains("不能为空")) {
			return "支付密码不能为空！";
		}
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");

		pocket.setPuid(uid);
		result = pocketService.bindingBankCard(pocket);
		return result;
	}

	/**
	 * 验证支付密码是否正确
	 */
	@RequestMapping("/verifyPass")
	@ResponseBody
	public String verifyPass(Pocket pocket) {
		String result = "支付密码有误！";
		if (pocket.getPass() == null || pocket.getPass().length() == 0) {
			return "支付密码不能为空！";
		}
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");

		pocket.setPuid(uid);
		Pocket po = pocketService.findPocketByPuid(pocket);
		if (po.getPass().equals(pocket.getPass())) {
			return "验证成功！";
		}
		return result;
	}

	/**
	 * 提现 withdrawal
	 */
	@RequestMapping("/withdrawal")
	@ResponseBody
	public String withdrawal(Pocket pocket) {
		// 校验支付密码
		String result1 = verifyPass(pocket);
		if (!result1.contains("成功")) {
			return result1;
		}
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");

		Pocket pocket1 = new Pocket();
		pocket1.setPuid(uid);
		Pocket po = pocketService.findPocketByPuid(pocket1);
		int money = po.getMoney();// 钱包余额
		int cardmoney = po.getCardmoney();// 银行卡余额
		if (pocket.getMoney() > money) {
			return "取现金额不能大于余额！";
		}
		po.setMoney(money - pocket.getMoney());
		po.setCardmoney(cardmoney + pocket.getMoney());
		String result = pocketService.withdrawal(po);
		return result;
	}

	/**
	 * 钱包余额充值 需要前端 充值金额
	 * 
	 * @param response
	 * @return
	 */
	@RequestMapping("/pay")
	public void pay(Pocket pocket, HttpServletResponse response, HttpServletRequest request) throws Exception {

		// 支付请求
		// 获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				AlipayConfig.sign_type);
		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		String bb = new Date().getTime() + "" + (Math.floor(Math.random() * 90) + 10);
		String ordernumber = bb.substring(0, 15);
		pocket.setOrdernumber(ordernumber);
		// 保存商户订单号
		pocketService.updateOrdernumber(pocket);

		// String ordernumber = (String) session.getAttribute("ordernumber");
		String totalPrice = pocket.getMoney() + "";

		String subject = "YogaApp";
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + ordernumber + "\"," + "\"total_amount\":\"" + totalPrice
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();
		// 输出
		response.getWriter().println(result);
		// 调用充值方法

	}

	/**
	 * 支付宝 异步方法
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/notify")
	public void updateOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,
				AlipayConfig.sign_type); // 调用SDK验证签名

		// ——请在这里编写您的程序（以下代码仅作参考）——

		/*
		 * 实际验证过程建议商户务必添加以下校验： 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		 * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		 * 3、校验通知中的seller_id（或者seller_email)
		 * 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		 * 4、验证app_id是否为该商户本身。
		 */
		if (signVerified) {// 验证成功
			// 商户订单号
			String ordernumber = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

			// 交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
			// 交易金额
			String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

			/*
			 * if(trade_status.equals("TRADE_FINISHED")){ //判断该笔订单是否在商户网站中已经做过处理
			 * //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			 * //如果有做过处理，不执行商户的业务程序
			 * 
			 * //注意： //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知 }else
			 */

			if (trade_status.equals("TRADE_SUCCESS")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 如果有做过处理，不执行商户的业务程序
				// 将用户支付信息存储在数据库

				/*
				 * System.out.println("流水号：" + out_trade_no);
				 * System.out.println("支付宝交易号：" + trade_no);
				 * System.out.println("交易金额：" + total_amount);
				 * 
				 * out_trade_no
				 */
				int uid = pocketService.findPuidByOrdernumber(ordernumber);

				double money1 = Double.parseDouble(total_amount);
int money=(int) money1;
				payMoney(uid, money);

			}

			response.getWriter().println("success");

		} else {// 验证失败
			response.getWriter().println("fail");
			// 调试用，写文本函数记录程序运行情况是否正常
			// String sWord = AlipaySignature.getSignCheckContentV1(params);
			// AlipayConfig.logResult(sWord);

		}

	}

	/**
	 * 同步跳转
	 * 
	 * @param response
	 */
	@RequestMapping("/syn")
	public void syn(HttpServletResponse response) {
		try {
			response.sendRedirect("http://localhost:8080/pocket.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 充值余额 或者支付

	public void payMoney(int uid, int money) {
		System.out.println(uid);
		Pocket pocket = new Pocket();
		pocket.setPuid(uid);
		Pocket po = pocketService.findPocketByPuid(pocket);
		pocket.setMoney(money + po.getMoney());
		// 修改金额
		pocketService.rechargeMoney(pocket);
	}

}
